#include "netmanager.h"
#include "serverthread.h"
#include <QDebug>

NetManager::NetManager(QObject *parent)
    : QObject(parent),
    tcpServer(new QTcpServer(this))
{
    connect(tcpServer, &QTcpServer::newConnection, this, &NetManager::onNewConnection);
}

NetManager::~NetManager()
{
    tcpServer->close();
}

bool NetManager::startServer(quint16 port)
{
    if (!tcpServer->listen(QHostAddress::Any, port)) {
        qDebug() << "启动服务器失败:" << tcpServer->errorString();
        return false;
    }
    qDebug() << "服务器已启动，端口：" << port;
    return true;
}

void NetManager::onNewConnection()
{
    QTcpSocket *clientSocket = tcpServer->nextPendingConnection();
    qDebug() << "来自" << clientSocket->peerAddress().toString() << "的新连接";

    ServerThread *handler = new ServerThread(clientSocket);  // 创建一个新的线程处理器
    connect(handler, &ServerThread::finished, handler, &QObject::deleteLater);
    handler->start();  // 启动线程
}
